<?php

// +----------------------------------------------------------------------
// | 功能说明"
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2030 http://www.jmzh1688.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: lxl
// +----------------------------------------------------------------------


/**
 * 读取JSON文件,文件读写
 * @param $param
 * @return array
 */
function readjsonfile($jsonfile)
{
    if(file_exists($jsonfile))
    {
        $json_string = file_get_contents($jsonfile);  
        $data = json_decode($json_string, true);
        return $data;

    }
    else
    {
        return null;
    }

}


/**
 * 读取html文件,文件读写
 * @param $param
 * @return array
 */
function readhtmlfile($jsonfile)
{
    if(file_exists($jsonfile))
    {
        $json_string = file_get_contents($jsonfile);  
       
        return $json_string;

    }
    else
    {
        return "";
    }

}
/**
 * 写入HTML,文件读写
 * @param $param
 * @return array
 */
function writehtmlfile($jsonfile,$content)
{
$myfile = fopen($jsonfile, "w+") or die("Unable to open file!");
fwrite($myfile,$content);
fclose($myfile);
}



/**
 * 写入JSON文件,文件读写
 * @param $param
 * @return array
 */
function writejsonfile($jsonfile,$content)
{
$myfile = fopen($jsonfile, "w+") or die("Unable to open file!");
fwrite($myfile,$content);
fclose($myfile);
}


/**
 * 遍历文件
 * @param $param
 * @return array
 */
function myScanChildFile($dir)
{
    $dh  = opendir($dir);
    $tmp_arr = [];
    while (false !== ($filename = readdir($dh))) {
        if($filename !=".." && $filename !="."){
            if(is_dir($dir."/".$filename)){
               
            }else{
                $tmp_arr[] = $filename;
            }
        }

    }
    closedir($dh);
    return $tmp_arr;
}

/**
 * 遍历目录
 * @param $param
 * @return array
 */
function myScanChildDir($dir)
{
    $dh  = opendir($dir);
    $tmp_arr = [];
    while (false !== ($filename = readdir($dh))) {
        if($filename !=".." && $filename !="."){
            if(is_dir($dir."/".$filename)){
                $tmp_arr[] = $filename;
            }else{
              
            }
        }

    }
    closedir($dh);
    return $tmp_arr;
}


function myCreateDir($path)
{
    if (is_dir($path)){  
        return true;
    }else{
        $res=mkdir($path,0777,true); 
        if ($res){
            return true;
        }else{
            return false;
        }
    }
    return false;
}

/**
 * 遍历目录及文件
 * @param $param
 * @return array
 */
function myScanDirAndFile($dir)
{
    $dh  = opendir($dir);
    $tmp_arr = [];
    while (false !== ($filename = readdir($dh))) {
        if($filename !=".." && $filename !="."){
            if(is_dir($dir."/".$filename)){
                $tmp_arr[$filename] = myScanDirAndFile($dir."/".$filename);
            }else{
                $tmp_arr[] = $filename;
            }
        }

    }
    closedir($dh);
    return $tmp_arr;
}


/**
 * 数组操作函数
 * $arr1,$arr2键相同时更新第二个
 * @param $param
 * @return array
 */
function addarray($a1,$a2)
{
    if($a2==null){return $a1;}
    $result=array_merge($a1,$a2);
     return $result;
}





/**
 * 时间整数
 * @param $param
 * @return array
 */

function getintTime()
{
    return time();
}





/**
 * 菜单二级处理
 * @param $param
 * @return array
 */
function doListLeftMenu($param,$idstr='')
{
    $param =  json_decode(json_encode($param), true);
    $parent = []; $child = [];

    foreach($param as $key=>$vo){

        $vo['ischeck'] = '';
        if($idstr!=null&&strpos(",,".$idstr.",",",".$vo['id'].",")>0)
        {
            $vo['ischeck'] = 'true';
        }

        if(0 == $vo['parentid']){
            $vo['url'] = '#';
            $parent[] = $vo;
        }else{
            if(empty($vo['url']))
            {
                $vo['url'] = url($vo['controller'] .'/'. $vo['action']); 
            }
           
            $child[] = $vo;
        }

    }

    foreach($parent as $key=>$vo){
        foreach($child as $k=>$v){
            if($v['parentid'] == $vo['id']){
                $parent[$key]['child'][] = $v;
            }
        }
    }
    unset($child);
    return $parent;
}



/**
 * 菜单三级处理，深度处理
 * @param $param
 * @return array
 */
function doListMenu($param)
{
   $param =  json_decode(json_encode($param), true);
    $parent = []; $child = [];

 
   $parentfirstid=[];
    foreach($param as $key=>$vo){
          $param[$key]['deeps']=3;
        if(0 == $vo['parentid']){
           $param[$key]['deeps']=1;
           $parentfirstid[$vo["id"]]=$vo["id"];
        }
         
    }
    
    
    foreach($param as $key=>$vo){
      
        if(3 == $vo['deeps'] &&array_key_exists($vo['parentid'],$parentfirstid) ){
        	
           $param[$key]['deeps']=2;
           
        }
        
    }
    
    
    
    return $param;
    
    
    
}
/**
 * 菜单二级处理
 * @param $param
 * @return array
 */
function doListMenu2($param)
{
    $param =  json_decode(json_encode($param), true);
    $parent = []; $child = [];

 
   
    foreach($param as $key=>$vo){

        if(0 == $vo['parentid']){
           // $vo['url'] = '#';
            $parent[] = $vo;
        }else{
          //  $vo['url'] = url($vo['controller'] .'/'. $vo['action']); 
            $child[] = $vo;
        }
    }

    foreach($parent as $key=>$vo){
        foreach($child as $k=>$v){
            if($v['parentid'] == $vo['id']){
                $parent[$key]['child'][] = $v;
            }
        }
    }
    unset($child);


    $newparent = []; 
    foreach ($parent as $key=>$vo) {
        if (0 == $vo['parentid']) {
            $newparent[] = $vo;

            if(!empty($parent[$key]['child'])){
                foreach ($parent[$key]['child'] as $key2=>$vo2) {
                    $newparent[] = $vo2;
                }
    
            }
         
        }
    }


    return $newparent;
}



 function getWhereForm($param)
    {
        $where = [];
        foreach($param as $key=>$vo){
            if(strtolower($key)==strtolower("pageSize") ){continue;}
            if(strtolower($key)==strtolower("pageNumber") ){continue;}
            if($vo=="" ){continue;}

            $nkey=$key;
            $pos = strpos($key, '%'); if ($pos) { 
                 $nkey=substr($key,0,$pos); 
                 $where[$nkey]=array('like','%'.$vo.'%');
                 continue;
            }


            $pos = strpos($key, '<'); if ($pos) { 
                $nkey=substr($key,0,$pos); 
                $where[$nkey]=array('elt',$vo);
                continue;
           }

           $pos = strpos($key, '>'); if ($pos) { 
            $nkey=substr($key,0,$pos); 
            $where[$nkey]=array('egt',$vo);
            continue;
       }

         $where[$key]=$vo;
          
         }

         return $where;

    }

/**
 *数字金额转换成中文大写金额的函数
 *String Int  $num  要转换的小写数字或小写字符串
 *return 大写字母
 *小数位为两位
 **/
function toChineseNumber($num){
    $c1 = "零壹贰叁肆伍陆柒捌玖";
    $c2 = "分角元拾佰仟万拾佰仟亿";
    $num = round($num, 2);
    $num = $num * 100;
    if (strlen($num) > 10) {
        return "数据太长，没有这么大的钱吧，检查下";
    }
    $i = 0;
    $c = "";
    while (1) {
        if ($i == 0) {
            $n = substr($num, strlen($num)-1, 1);
        } else {
            $n = $num % 10;
        }
        $p1 = substr($c1, 3 * $n, 3);
        $p2 = substr($c2, 3 * $i, 3);
        if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
            $c = $p1 . $p2 . $c;
        } else {
            $c = $p1 . $c;
        }
        $i = $i + 1;
        $num = $num / 10;
        $num = (int)$num;
        if ($num == 0) {
            break;
        }
    }
    $j = 0;
    $slen = strlen($c);
    while ($j < $slen) {
        $m = substr($c, $j, 6);
        if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
            $left = substr($c, 0, $j);
            $right = substr($c, $j + 3);
            $c = $left . $right;
            $j = $j-3;
            $slen = $slen-3;
        }
        $j = $j + 3;
    }

    if (substr($c, strlen($c)-3, 3) == '零') {
        $c = substr($c, 0, strlen($c)-3);
    }
    if (empty($c)) {
        return "零元整";
    }else{
        return $c . "整";
    }
}

function genword($model,$id,$wordpath){
    $res =$model->get($id);
    $phpWord = new \PhpOffice\PhpWord\PhpWord();
    $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($wordpath);

    if($phpWord){
        foreach ($res->toarray() as $key => $value){
            $templateProcessor->setValue($key,$value);
        }
    }
    $path = $templateProcessor->save($wordpath);
    // 下载文件到浏览器
    if (!file_exists($path)){
        echo  "没有该文件";
        return;
    }else{
        ob_clean();
        ob_start();
        $filename =  $res['projec_title'].'.doc';
        $fp = fopen($path, "r");
        $file_size = filesize($path);
        Header("Content-type:  application/octet-stream ");
        Header("Accept-Ranges:  bytes ");
        Header("Accept-Length:".$file_size);
        Header("Content-Disposition:  attachment;  filename= $filename");
        $buffer=1024;
        $file_count=0;
        $file  = fopen($path, "r");
        while (!feof($file) && $file_count<$file_size) {
            $file_con=fread($fp,$buffer);
            $file_count +=$buffer;
            echo $file_con;
        }
        fclose($fp);
        ob_end_flush();
    }
}

function GetRandStr($length){
    $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $len=strlen($str)-1;
    $randstr='';
    for($i=0;$i<$length;$i++){
        $num=mt_rand(0,$len);
        $randstr .= $str[$num];
    }
    return $randstr;
}

function date_month_diff($begin, $end){
    if(!$begin || !$end) return FALSE;
    $begin = intval($begin);
    $end= intval($end);
    //计算月份差
    $mon = date('m', $end) - date('m', $begin);
    //计算月份差
    $day = date('d', $end) - date('d', $begin);
    //计算年份差
    $y  = date('y', $end) - date('y', $begin);
    //如果结束日期的天  减去  开始时间的天数   小于  0   &&  并且 月份相减的差 等于 1
    if($day < 0 && $mon == 1){
        //begin的当月最大天数
        $begin_m_d_n = date('t', $begin);
        //begin的当天数值
        $begin_day = date('d', $begin);
        $day = (date('d', $end)) + ($begin_m_d_n  - $begin_day);
    }
    //如果年份不同
    if( $y>0){
        //累加月份
        $mon +=  $y*12;
    }
    $datedif = array('mon' => $mon, 'day' => $day);
    return $datedif;
}


function get_weekend_days($start_date, $end_date, $weekend_days=2) {

    $data = array();
    if (strtotime($start_date) > strtotime($end_date)) list($start_date, $end_date) = array($end_date, $start_date);

    $start_reduce = $end_add = 0;
    $start_N      = date('N',strtotime($start_date));
    $start_reduce = ($start_N == 7) ? 1 : 0;

    $end_N = date('N',strtotime($end_date));

    // 进行单、双休判断，默认按单休计算
    $weekend_days = intval($weekend_days);
    switch ($weekend_days)
    {
        case 2:
            in_array($end_N,array(6,7)) && $end_add = ($end_N == 7) ? 2 : 1;
            break;
        case 1:
        default:
            $end_add = ($end_N == 7) ? 1 : 0;
            break;
    }

    $days = round(abs(strtotime($end_date) - strtotime($start_date))/86400) + 1;
    $data['total_days'] = $days;
    $data['total_relax'] = floor(($days + $start_N - 1 - $end_N) / 7) * $weekend_days - $start_reduce + $end_add;

    return $data;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
    $result = false;
    if(is_dir($dir_name)){
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}


//生成类似uuid的随机字符串
function uuid($prefix = '')
{
    $chars = md5(uniqid(mt_rand(), true));
//    $uuid  = substr($chars,0,8) . '-';
//    $uuid .= substr($chars,8,4) . '-';
//    $uuid .= substr($chars,12,4) . '-';
//    $uuid .= substr($chars,16,4) . '-';
//    $uuid .= substr($chars,20,12);
    return $prefix . $chars;
}

/**
 * 无限极分类处理成树形结构
 * @param $data         需要处理的数据
 * @param $pId          上级id值 0 是第一级
 * @param $parentkeyid  父级id主键
 * @param $keyid        主键ID
 * @return array
 */
function getTree($data, $pId,$parentkeyid,$keyid)
{
    $tree = array();
    foreach($data as $k => $v)
    {

        if($v[$parentkeyid] == $pId)
        {
            $v['children'] = getTree($data, $v[$keyid],$parentkeyid,$keyid);
            $tree[] = $v;
            unset($data[$k]);
        }
    }
    return $tree;
}

/**
 * 无限极分类处理成树形结构
 * @param $data         需要处理的数据
 * @param $pId          上级id值 0 是第一级
 * @param $parentkeyid  父级id主键
 * @param $keyid        主键ID
 * @return array
 */
function getTree_track($data, $pId,$parentkeyid,$keyid,$threshold)
{
    static $level = 0;
    $tree = array();
    foreach($data as $k => $v)
    {
        if(empty($threshold)){
            if($v[$parentkeyid] == $pId)
            {
                $v['children'] = getTree_track($data, $v[$keyid],$parentkeyid,$keyid,$threshold);
                $tree[] = $v;
                unset($data[$k]);
            }
        }else{
//            echo count($data);
            echo $pId;
            if($v[$keyid] == $threshold){
                unset($data[$k]);
                $tree=$v;
                $tree['children'] = getTree_track($data, $v[$keyid],$parentkeyid,$keyid,$threshold);
                unset($data[$k]);
            }elseif($v[$parentkeyid] == $pId){
                unset($data[$k]);
                $v['children'] = getTree_track($data, $v[$keyid],$parentkeyid,$keyid,$threshold);
                $tree[] = $v;
                unset($data[$k]);
             }
        }


    }
    return $tree;
}

/**
 * treeselect 树形结构下拉框
 * @param $data         需要处理的数据
 * @param $pId          上级id值 0 是第一级
 * @param $parentkeyid  父级id主键
 * @param $keyid        主键ID
 * @return array
 */
function getTree2($data, $pId,$parentkeyid,$keyid)
{
    $tree = array();
    foreach($data as $k => $v)
    {
        $v['open'] =false;
        $v['checked'] =true;
        if(!empty($v['title'])){
            $v['name'] =$v['title'];
        }
        if($v[$parentkeyid] == $pId)
        {
            $d = getTree2($data, $v[$keyid],$parentkeyid,$keyid);

            if($d){
                $v['children'] =$d;
            }

            $tree[] = $v;
            unset($data[$k]);
        }
    }
    return $tree;
}